<script setup lang="ts">
import { ref, onMounted } from 'vue'
import CourseCard from './CourseCard.vue'
import { getCourseList } from '@/services/home.ts'
import { useMemberStore } from '@/stores'
import { formatDate } from '@/utils'
import type { CourseItem, CourseParams } from '@/types/course'
import ArchiveCard from '../../growthArchive/components/ArchiveCard.vue'
import { getArchiveList } from '@/services/home.ts'
import type { ArchiveItem, ArchiveParams } from '@/types/archive'
//当前登录用户
const memberStore = useMemberStore()
// 状态管理
const isLoading = ref(false)
const isTriggered = ref(false)
const serviceItems = ref([
  {
    icon: 'https://167nj97th156.vicp.fun/profile/upload/calendar.png',
    name: '课表',
    color: '#409EFF',
    url: '/pages/myCourse/course',
  },
  {
    icon: 'https://167nj97th156.vicp.fun/profile/upload/homework.png',
    name: '课后作业',
    color: '#FF7D00',
    url: '/pages/homework/index',
  },
  {
    icon: 'https://167nj97th156.vicp.fun/profile/upload/laoshipingjia.png',
    name: '评价老师',
    color: '#409EFF',
    url: '/pages/teacher/teacher',
  },
  {
    icon: 'https://167nj97th156.vicp.fun/profile/upload/chengzhangdangan.png',
    name: '成长档案',
    color: '#909399',
    url: '/pages/growthArchive/index',
  },
  {
    icon: 'https://167nj97th156.vicp.fun/profile/upload/ketangdianping.png',
    name: '课堂点评',
    color: '#909399',
    url: '/pages/growthArchive/index',
  },
  {
    icon: 'https://167nj97th156.vicp.fun/profile/upload/shangkejilu.png',
    name: '上课记录',
    color: '#FF7D00',
    url: '/pages/classRecord/classRecord',
  },

  {
    icon: 'https://167nj97th156.vicp.fun/profile/upload/qingjia.png',
    name: '请假',
    color: '#909399',
    url: '/pages/classLeave/index',
  },
  {
    icon: 'https://167nj97th156.vicp.fun/profile/upload/jifenlipin.png',
    name: '积分礼品',
    color: '#FF7D00',
    url: '/pages/points/gift',
  },
])
const courseList = ref<CourseItem[]>([])
const format = 'YYYY-MM-DD HH:mm:ss'
// 分页参数
const coursePage = ref<CourseParams>({
  pageNum: 1,
  pageSize: 100,
  startDatetime: formatDate(new Date(), format),
})
// 获取课程列表
const getCourseListData = async (pageParams: CourseParams) => {
  pageParams.studentId = memberStore.profile?.userId
  // 如果是下拉刷新，清空现有数据
  if (pageParams.pageNum === 1) {
    courseList.value = []
  }
  try {
    const res = await getCourseList(pageParams)
    // 添加数据
    if (pageParams.pageNum === 1) {
      courseList.value = res.data.rows
    } else {
      courseList.value = [...courseList.value, ...res.data.rows]
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
  }
}
// 成长档案列表
const archiveList = ref<ArchiveItem[]>([])
// 分页参数
const archivePage = ref<ArchiveParams>({ pageNum: 1, pageSize: 100 })
// 获取成长档案列表
const getArchiveListData = async (pageParams: ArchiveParams) => {
  // 登录状态下，添加 studentId 参数
  pageParams.studentId = memberStore.profile?.userId
  pageParams.studyStatus = 4
  // 如果是下拉刷新，清空现有数据
  if (pageParams.pageNum === 1) {
    archiveList.value = []
  }

  try {
    const res = await getArchiveList(pageParams)
    // 添加数据
    if (pageParams.pageNum === 1) {
      archiveList.value = res.data.rows
    } else {
      archiveList.value = [...archiveList.value, ...res.data.rows]
    }
    // 更新页码
    archivePage.value.pageNum = pageParams.pageNum
  } catch (error) {
    console.error('获取消息列表失败:', error)
  }
}
// 生命周期
onMounted(async () => {
  isLoading.value = true
  await Promise.all([getCourseListData(coursePage.value), getArchiveListData(archivePage.value)])
  isLoading.value = false
})

// 下拉刷新处理
const onRefresherrefresh = async () => {
  isTriggered.value = true
  await Promise.all([getCourseListData(coursePage.value), getArchiveListData(archivePage.value)])
  // 关闭动画
  isTriggered.value = false
}

const currentTab = ref('today') // 'today' | 'tomorrow'
// 切换标签
const switchTab = (tab: 'today' | 'tomorrow') => {
  currentTab.value = tab
  // 切换标签时如果对应列表为空，则加载数据
  if (tab === 'today') {
    coursePage.value.startDatetime = formatDate(new Date(), format)
  } else {
    coursePage.value.startDatetime = formatDate(
      new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
      format,
    )
  }
  coursePage.value.pageNum = 1
  coursePage.value.pageSize = 100
  getCourseListData(coursePage.value)
}
// 添加导航方法
const navigateToSchedule = () => {
  uni.navigateTo({ url: '/pages/myCourse/course' })
}

const navigateToArchive = () => {
  uni.navigateTo({ url: '/pages/growthArchive/index' })
}
</script>

<template>
  <scroll-view
    class="page-container"
    :scroll-y="true"
    :refresher-enabled="true"
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
  >
    <!-- 服务图标区域 -->
    <view class="service-grid card-common">
      <navigator
        class="service-item"
        hover-class="none"
        :url="item.url"
        v-for="(item, index) in serviceItems"
        :key="index"
      >
        <view class="icon-container" :style="{ backgroundColor: item.color + '15' }"
          ><!-- 使用颜色值加透明度作为背景 -->
          <image class="icon" :src="item.icon"></image>
        </view>
        <text class="service-name">{{ item.name }}</text>
      </navigator>
    </view>

    <!-- 课表速览 -->
    <view class="section-container card-common">
      <view class="section-header flex-row justify-between items-center">
        <text class="section-title">今日课表</text>
        <text class="more-link" @click="navigateToSchedule">{{ '更多>' }}</text>
      </view>
      <view class="schedule-tabs">
        <view
          class="tab-item"
          :class="{ active: currentTab === 'today' }"
          @click="switchTab('today')"
          >今天</view
        >
        <view
          class="tab-item"
          :class="{ active: currentTab === 'tomorrow' }"
          @click="switchTab('tomorrow')"
          >明天</view
        >
      </view>
      <view class="schedule-content">
        <CourseCard v-for="course in courseList" :key="course.id" :course="course" />
        <view class="empty-state" v-if="courseList.length === 0 && !isLoading">
          <image class="empty-icon" src="@/static/images/empty.png"></image>
          <text class="empty-text">暂无课程</text>
        </view>
      </view>
    </view>

    <!-- 成长档案 -->
    <view class="section-container card-common">
      <view class="section-header flex-row justify-between items-center">
        <text class="section-title">成长档案</text>
        <text class="more-link" @click="navigateToArchive">{{ '更多>' }}</text>
      </view>
      <view class="growth-archive">
        <ArchiveCard v-for="archive in archiveList" :key="archive.id" :archive="archive" />
        <view class="empty-state" v-if="archiveList.length === 0 && !isLoading">
          <image class="empty-icon" src="@/static/images/empty.png"></image>
          <text class="empty-text">暂无成长档案</text>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import '../styles/index.scss';
</style>
